<script lang="ts" setup>
import { ElMessage } from 'element-plus';

import SubViewContainer from '@core/components/subLayout/SubViewContainer.vue';
import Order from '@core/engine/Order';
import Session from '@core/engine/Session';
import * as Enums from '@firewall/engine/Enums';
import OrderHelper from '@firewall/utils/OrderHelper';
import { orderConfirmStore, OrderDetail } from '@firewall/stores/order';

const { t } = useI18n({ inheritLocale: true, useScope: 'local' });

const orderToConfirm: Partial<OrderDetail> = reactive({});
const isAgreedToAgreement = ref(false);

const AutoRenewDefaultCount = {
  ByMonth: 3,
  ByYear: 1,
};
const regionName = Session.getRegionName();

const submitOrder = async () => {
  const order = orderToConfirm as OrderDetail;
  const { type: cycleType, count: cycleCount } = OrderHelper.getCycleConfig(order.purchaseDuration);
  const { autoRenewCycleType, autoRenewCycleCount } = getOrderAutoRenewConfig(order, cycleType);
  const orderParams = OrderHelper.buildOrderParams({
    cycleType,
    cycleCount,
    masterConfig: order,
    protectionIpCount: order.protectionIpCount,
    flowProcessingCapacity: order.flowProcessingCapacity,
  });
  if (!orderParams) {
    return;
  }
  const params = {
    autoPay: false,
    autoRenewStatus: order.autoRenewStatus,
    autoRenewCycleCount,
    autoRenewCycleType,
    orders: [orderParams],
  };
  const response = await Order.placeNewPurchaseOrder(params);
  Order.openOrderDetailPage(response.newOrderId);
};

const getOrderAutoRenewConfig = (order: OrderDetail, cycleType: number) => {
  let autoRenewCycleType = 0;
  let autoRenewCycleCount = 0;
  if (order.autoRenewStatus === Enums.RequestBoolean.True) {
    if (cycleType === Enums.OrderCycleType.Month) {
      autoRenewCycleCount = AutoRenewDefaultCount.ByMonth;
      autoRenewCycleType = Enums.OrderCycleType.Month;
    } else {
      autoRenewCycleCount = AutoRenewDefaultCount.ByYear;
      autoRenewCycleType = Enums.OrderCycleType.Year;
    }
  }
  return { autoRenewCycleType, autoRenewCycleCount };
};

onMounted(() => {
  Object.assign(orderToConfirm, orderConfirmStore().order);
});

const router = useRouter();
const isSubmitting = ref(false);
const onOrderNow = async () => {
  if (!isAgreedToAgreement.value) {
    return ElMessage.warning(t('noAgreedMessage'));
  }
  isSubmitting.value = true;
  try {
    await submitOrder();
    router.push({ name: 'configCenter.quota' });
  } finally {
    isSubmitting.value = false;
  }
};
</script>
<template>
  <SubViewContainer>
    <ElCard v-loading="isSubmitting">
      <ElTable size="small" :data="[orderToConfirm]">
        <ElTableColumn :label="t('product')">
          <template #default>{{ t('firewallQuota') }}</template>
        </ElTableColumn>
        <ElTableColumn :label="t('config')">
          <template #default="scope">
            <div class="config">
              <div>{{t('region') + ': ' + regionName}}</div>
              <div>{{t('vpc') + ': ' + scope.row.vpcName + "(" + scope.row.vpcIp + ")"}}</div>
              <div>{{t('version') + ': ' + t(`firewallEdition.${scope.row.firewallEdition}`)}}</div>
              <div>{{t('defenseIpCountStats') + ': ' + scope.row.protectionIpCount}}</div>
              <div>{{t('internetFlowProcessingCapacity') + ': ' + scope.row.flowProcessingCapacity + t('mbps')}}</div>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn :label="t('duration')">
          <template #default="scope">{{ scope.row.purchaseDurationText }}</template>
        </ElTableColumn>
        <ElTableColumn :label="t('totalPrice')">
          <template #default="scope">{{ t('quantifierOfMoney') + scope.row.totalPrice }}</template>
        </ElTableColumn>
      </ElTable>
      <ElRow class="tip-row" align="middle">
        <ElCheckbox v-model="isAgreedToAgreement" :label="t('agreementTip')" />
        <ElLink type="primary">{{t('serviceAgreement')}}</ElLink>
      </ElRow>
      <ElRow class="buttons">
        <ElButton type="primary" :disabled="!isAgreedToAgreement" @click="onOrderNow">{{t('confirmOrder')}}</ElButton>
        <RouterLink :to="{ name: 'configCenter.quota.purchase' }">
          <ElButton>{{t('cancel')}}</ElButton>
        </RouterLink>
      </ElRow>
    </ElCard>
  </SubViewContainer>
</template>

<i18n lang="yaml" locale="zh-CN">
  product: '产品'
  firewallQuota: '云防火墙（原生版）'
  config: '配置'
  region: '地域'
  duration: '时长'
  totalPrice: '总价'
  vpc: '虚拟私有云'
  version: '版本'
  firewallEdition:
    AdvancedEdition: '高级版'
  firewallName: '云防火墙名称'
  defenseIpCountStats: '可防护公网IP数'
  internetFlowProcessingCapacity: '公网流量处理能力'
  cancel: '取消'
  confirmOrder: '确认订购'
  advancedEdition: '高级版'
  agreementTip: '我已阅读并同意相关协议'
  serviceAgreement: '《天翼云云防火墙（原生版）服务协议》'
  quantifierOfMoney: '￥'
  noAgreedMessage: '请阅读并同意服务协议'
  month: '{n} 个月'
  year: '{n} 年'
  mbps: 'Mbps'
</i18n>

<style lang="scss" scoped>
.el-table {
  margin-bottom: 10px;
}

.tip-row {
  margin-bottom: 10px;

  :deep(.el-checkbox__label),
  .el-link {
    font-size: 12px;
  }
}

.buttons {
  .el-button {
    margin-right: 10px;
  }
}
</style>
